package com.ljx.demo.security.custom;

import com.ljx.demo.domain.entity.User;
import com.ljx.demo.security.core.LoginUser;
import com.ljx.demo.security.core.UserHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-06-16  23:07
 */
@Service
public class CustomUserDetailService implements UserDetailsService{

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 检验账号状态
        // 查询数据库检验账户密码的正确性
        // ...

        Authentication context = UserHolder.getContext();
        return new LoginUser(new User(context.getName(), new BCryptPasswordEncoder().encode(context.getCredentials().toString())),
                getPermsList());
    }

    /**
     * 模拟用户拥有的权限
     * @return
     */
    private Set<String> getPermsList() {
        Set<String> res = new HashSet<>();
        res.add("user:t1");
        res.add("user:t2");

        return res;
    }
}
